package com.yumei.trader.gym.google;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.Nullable;

import com.android.billingclient.api.AcknowledgePurchaseParams;
import com.android.billingclient.api.AcknowledgePurchaseResponseListener;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;

import java.security.PublicKey;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

public class GoogleHelper implements PurchasesUpdatedListener {

    private BillingClient mBillingClient;

    /** 购买验证用的公钥 */
    private PublicKey mPublicKey;

    private BillingResultCallBack callBack;

    private static GoogleHelper instance;

    private SkuDetails skuDetails = null;

    private GoogleHelper(Context context, String base64PublicKey){

        try {
            mPublicKey = Security.generatePublicKey(base64PublicKey);

            mBillingClient = BillingClient.newBuilder(context)
                    .enablePendingPurchases()
                    .setListener(this)
                    .build();
        }catch (Exception e){
            e.printStackTrace();
        }

    }


    public static GoogleHelper initInstance(Context context, String base64PublicKey){

        if(instance == null){
            instance = new GoogleHelper(context,base64PublicKey);
        }

        return instance;
    }


    public static GoogleHelper sharedInstance(){
        return instance;
    }



    public void setResultCallback(BillingResultCallBack callback){
        this.callBack = callback;
    }


    public boolean isReady(){

        if(mBillingClient !=null){
            return mBillingClient.isReady();
        }

        return false;
    }

    public boolean connectGooglePlay(BillingClientStateListener listener){

        if (mBillingClient.isReady() ){
            return false;
        }
        mBillingClient.startConnection(listener);

        return true;
    }



    /**
     * 查询指定商品
     * @param sku
     */
    public void executeQuerySkuDetails(String sku, SkuDetailsResponseListener listener){

        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(Collections.singletonList(sku));
        params.setType(BillingClient.SkuType.SUBS);
        mBillingClient.querySkuDetailsAsync(params.build(),listener);
    }

    /**
     * 查询指定商品
     * @param skuArr 商品Id数组
     */
    public void executeQuerySkuDetails(List<String> skuArr, SkuDetailsResponseListener listener){

        SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder();
        params.setSkusList(skuArr);
        params.setType(BillingClient.SkuType.INAPP);
        mBillingClient.querySkuDetailsAsync(params.build(),listener);
    }

    /**
     * 查询指定已订阅商品
     */
    public boolean executeQueryPurchases(final String sku){


        return false;
    }


    /**
     * 执行购买
     * @param activity
     * @param skuDetails
     */
    public void launchBillingFlow(final Activity activity, final SkuDetails skuDetails){

        if(areSubscriptionsSupported()) {

            this.skuDetails = skuDetails;
            System.out.println("id="+skuDetails.getSku());

            BillingFlowParams flowParams = BillingFlowParams.newBuilder()
                    .setSkuDetails(skuDetails)
                    .build();

            BillingResult billingResult = mBillingClient.launchBillingFlow(activity, flowParams);

            int code = billingResult.getResponseCode();

            System.out.println(" ======= launchBillingFlow  code = "+code);

        }else{
            System.out.println(" net support ");
        }
    }


    /**
     * 批量确认购买！必须在三天内确认
     * @param purchases  购买信息
     * @param payload    开发者自定义信息
     */
    public void acknowledge(List<Purchase> purchases, final String payload) {

        if (purchases == null || purchases.size() == 0) {
            return;
        }
        for (Purchase purchase : purchases) {
            if (purchase.isAcknowledged()) continue;
            acknowledge(purchase, payload);
        }
    }



    /**
     * 确认购买
     * @param purchase
     * @param payload
     */
    public  void  acknowledge(final Purchase purchase, final String payload){

        if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) {
            if (purchase.isAcknowledged()){
               return;
            }
        }

        AcknowledgePurchaseParams acknowledgePurchaseParams =
                AcknowledgePurchaseParams.newBuilder()
                        .setPurchaseToken(purchase.getPurchaseToken())
                        .build();

        mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
            @Override
            public void onAcknowledgePurchaseResponse(BillingResult billingResult) {

                int code = billingResult.getResponseCode();

                System.out.println("onAcknowledgePurchaseResponse code="+code);

                if (BillingClient.BillingResponseCode.OK == code) {

                }
            }
        });
    }





    /**
     * 消息商品
     * @param purchase
     * @param payload
     */
    public void consume(final Purchase purchase, final String payload){

        ConsumeParams consumeParams = ConsumeParams.newBuilder()
                .setPurchaseToken(purchase.getPurchaseToken())
                .build();

        mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
            @Override
            public void onConsumeResponse(BillingResult billingResult, String purchaseToken) {
                int code = billingResult.getResponseCode();

            }
        });
    }


    private boolean areSubscriptionsSupported() {

        BillingResult featureSupported = mBillingClient.isFeatureSupported(BillingClient.FeatureType.SUBSCRIPTIONS);
        if (featureSupported.getResponseCode() != BillingClient.BillingResponseCode.OK) {
            System.out.println( "areSubscriptionsSupported() got an error response: " + featureSupported.getDebugMessage());
        }
        return featureSupported.getResponseCode() == BillingClient.BillingResponseCode.OK;
    }



    @Override
    public void onPurchasesUpdated(BillingResult billingResult, @Nullable List<Purchase> purchases) {

        int code = billingResult.getResponseCode();

        System.out.println("onPurchasesUpdated  code="+code+", list size=");

        if(callBack !=null){
            callBack.onResult(code,purchases);
        }

        if (BillingClient.BillingResponseCode.OK == code){

            if(purchases !=null){ //批量确认购买
                acknowledge(purchases, null);
            }

        } else if (BillingClient.BillingResponseCode.USER_CANCELED == code){

        } else{

        }
    }



}
